<template>
  <!-- 导航栏 -->
  <cp-nav-bar title="登录" rightText="注册" @click-right="$router.push('/register')"></cp-nav-bar>
  <div class="login">
    <!-- 登录部分 -->
    <div class="login-head">
      <h3>{{ isPass ? '密码登录' : '短信验证码登录' }}</h3>
      <a href="javascript:;" @click="isPass = !isPass">
        <span>{{ !isPass ? '密码登录' : '短信验证码登录' }} </span>
        <van-icon name="arrow"></van-icon>
      </a>
    </div>
    <!-- form 表单 -->
    <van-form autocomplete="off" @submit="login">
      <van-field
        v-model="mobile"
        :rules="mobileRules"
        placeholder="请输入手机号"
        type="tel"
        maxlength="11"
      ></van-field>
      <van-field
        v-if="isPass"
        v-model="password"
        :rules="passwordRules"
        placeholder="请输入密码"
        :type="show ? 'text' : 'password'"
        maxlength="16"
      >
        <template #button>
          <cp-icon @click="show = !show" :name="`login-eye-${show ? 'on' : 'off'}`"></cp-icon>
        </template>
      </van-field>
      <van-field
        v-else
        placeholder="请输入短信验证码"
        v-model="code"
        :rules="codeRules"
        maxlength="6"
      >
        {{ code }}
        <template #button>
          <span @click="send">{{ time === 0 ? '发送验证码' : time + 's后再次发送' }}</span>
        </template>
      </van-field>
      <div class="cp-cell">
        <van-checkbox v-model="agree">
          <span>我已同意</span>
          <a href="javascript:;">用户协议</a>
          <span>及</span>
          <a href="javascript:;">隐私条款</a>
        </van-checkbox>
      </div>
      <div class="cp-cell">
        <van-button block round type="primary" native-type="submit">登 录</van-button>
      </div>
      <div class="cp-cell">
        <a href="javascript:;">忘记密码？</a>
      </div>
    </van-form>
    <!-- ... -->
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { mobileRules, passwordRules, codeRules } from '@/utils/rules'
import { showFailToast, showSuccessToast, type FormInstance } from 'vant'
import { loginByMobile, loginByPassword, sendMobileCode } from '@/api/user'
import { useUserStore } from '@/stores/modules/user'
import { useRoute, useRouter } from 'vue-router'
import { onUnmounted } from 'vue'

// 是否同意协议
const agree = ref(false)
// 动态切换眼睛图标
const show = ref(false)
// 绑定表单数据
const mobile = ref('')
const password = ref('')
const isPass = ref(true)
const code = ref('')

// 存储token
const store = useUserStore()
// 跳转路由router === this.$router
const router = useRouter()
// 获取路由参数route === this.$route
const route = useRoute()
const login = async () => {
  if (!agree.value) {
    // Toast.fail('请同意用户协议') ——vant3.x中的写法
    // showFailToast('请同意用户协议') ——vant4.x中的写法
    showFailToast({
      message: '请同意用户协议',
      forbidClick: true
    })
    return
  }
  try {
    const res = isPass.value
      ? await loginByPassword(mobile.value, password.value)
      : await loginByMobile(mobile.value, code.value)
    store.setUser(res)
    router.push((route.query.returnUrl as string) || '/user')
    showSuccessToast('登录成功')
  } catch (err) {
    console.log(err)
  }
}

const form = ref<FormInstance>()
const time = ref(0)
let timer: number
// 发送验证码：验证手机合法性、节流
const send = async () => {
  // 为空 不执行
  if (!mobile.value) return
  // 不合法 不执行
  await form.value?.validate('mobile')
  // 节流
  // if (time.value > 0) return
  if (timer) return
  try {
    const res = await sendMobileCode(mobile.value, 'login')
    code.value = res.code
    console.log(code.value)
    showSuccessToast('发送成功')

    time.value = 60
    timer = setInterval(() => {
      time.value--
      if (time.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  } catch (err) {
    console.log(err)
  }
}
onUnmounted(() => clearInterval(timer))
</script>

<style lang="scss" scoped>
.login {
  padding-top: 46px;
  &-head {
    padding: 30px 30px 50px;
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    line-height: 1;
    h3 {
      font-weight: normal;
      font-size: 24px;
    }
    a {
      font-size: 15px;
    }
  }
  .van-form {
    padding: 0 14px;
    .cp-cell {
      height: 52px;
      padding: 14px 16px;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      .van-checkbox {
        a {
          color: var(--cp-primary);
          padding: 0 5px;
        }
      }
    }
  }
}
</style>
